﻿using System.Data;
using System.Diagnostics;
using System.Net.WebSockets;
using System.Security.Cryptography;
using System.Security.Policy;
using System.Text;
using System.Text.Json.Nodes;
using LitJson;
using Sunny.UI.Win32;


namespace Erp
{
    public partial class Model
    {
        private static HttpClient? client = new() { Timeout = TimeSpan.FromSeconds(10) };
        private static string token = string.Empty;
        private static ClientWebSocket ws = new();



        #region ·登录
        public async Task UserLogin()
        {
            StringContent content = null;
            HttpRequestMessage request = null;
            HttpResponseMessage response = null; ;
            JsonData jsonObj = null;
            try
            {
                content = new StringContent(@"{""sessionId"":"""",""username"":""18640194060"",""password"":""Malijia2!"",""graphicsCode"":""""}", Encoding.UTF8, "application/json");
                request = new HttpRequestMessage(HttpMethod.Post, "https://erp.yto.net.cn/steward/erp/users/userLogin");
                request.Content = content;
                request.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36 Edg/135.0.0.0");
                request.Headers.Add("Accept", "application/json");
                request.Headers.Add("accept-encoding", "gzip");
                response = await client.SendAsync(request);
                jsonObj = await response.Content.ToJsonObj();
                if (jsonObj["code"].ToString() == "200")
                {
                    token = jsonObj["data"]["token"].ToString();
                }
                else
                {
                    Controller.speech.SpeakAsync("账号登录失败");
                }
            }
            finally
            {
                if (null != content) content.Dispose();
                if (null != request) request.Dispose();
                if (null != response) response.Dispose();
                if (null != jsonObj) { jsonObj.Clear(); jsonObj = null; }
            }
        }
        #endregion

        #region ·获取数据
        public async Task 获取数据_待打印订单() 
        {
            var content = new StringContent(@"{""waybillPrintStatusList"":[0],""orderFlags"":[],""whId"":""1"",""platformCode"":"""",""mallCodes"":[],""buyerNicks"":[],""receiveMobileL4"":"""",""receiveName"":"""",""receiveMobile"":"""",""senderName"":"""",""senderPhone"":"""",""senderMobile"":"""",""productNameL"":"""",""skuNameL"":"""",""skuCodeL"":"""",""productCodeL"":"""",""goodsOrSkuCnt"":"""",""finderName"":"""",""deliverPrintStatusList"":[0,1],""hasGift"":"""",""orderTypeList"":[],""orderTags"":[],""hasWaybillNo"":"""",""hasExpress"":"""",""cpCodeTempId"":"""",""receiveAreas"":[],""supplierIds"":[],""distributorIds"":[],""pageIndex"":200,""pageNo"":1,""limit"":500,""orderByIndex"":""13""}", Encoding.UTF8, "application/json");
            var response = await ErpHttpRequest(content,"Page");
            response.To集合_View_订单();
        }
        public async Task 获取数据_待发货订单()
        {
            var content = new StringContent(@"{""waybillPrintStatusList"":[0,1],""orderFlags"":[],""whId"":""1"",""platformCode"":"""",""mallCodes"":[],""buyerNicks"":[],""receiveMobileL4"":"""",""receiveName"":"""",""receiveMobile"":"""",""senderName"":"""",""senderPhone"":"""",""senderMobile"":"""",""productNameL"":"""",""skuNameL"":"""",""skuCodeL"":"""",""productCodeL"":"""",""goodsOrSkuCnt"":"""",""finderName"":"""",""deliverPrintStatusList"":[0,1],""hasGift"":"""",""orderTypeList"":[],""orderTags"":[],""hasWaybillNo"":"""",""hasExpress"":"""",""cpCodeTempId"":"""",""receiveAreas"":[],""supplierIds"":[],""distributorIds"":[],""pageIndex"":200,""pageNo"":1,""limit"":500,""orderByIndex"":""13""}", Encoding.UTF8, "application/json");
            var response = await ErpHttpRequest(content, "Page");
            response.To集合_View_订单();
        }

        public async Task<string> 获取数据_待打印数量()
        {
            var content = new StringContent(@"{""waybillPrintStatusList"":[0],""orderFlags"":[],""whId"":""1"",""platformCode"":"""",""mallCodes"":[],""buyerNicks"":[],""receiveMobileL4"":"""",""receiveName"":"""",""receiveMobile"":"""",""senderName"":"""",""senderPhone"":"""",""senderMobile"":"""",""productNameL"":"""",""skuNameL"":"""",""skuCodeL"":"""",""productCodeL"":"""",""goodsOrSkuCnt"":"""",""finderName"":"""",""deliverPrintStatusList"":[0,1],""hasGift"":"""",""orderTypeList"":[],""orderTags"":[],""hasWaybillNo"":"""",""hasExpress"":"""",""cpCodeTempId"":"""",""receiveAreas"":[],""supplierIds"":[],""distributorIds"":[],""pageIndex"":200,""pageNo"":1,""limit"":500,""orderByIndex"":""13""}", Encoding.UTF8, "application/json");
            var response = await ErpHttpRequest(content, "Page");
            return response.Return_Count();
        }
        public async Task<string> 获取数据_待发货数量()
        {
            var content = new StringContent(@"{""waybillPrintStatusList"":[0,1],""orderFlags"":[],""whId"":""1"",""platformCode"":"""",""mallCodes"":[],""buyerNicks"":[],""receiveMobileL4"":"""",""receiveName"":"""",""receiveMobile"":"""",""senderName"":"""",""senderPhone"":"""",""senderMobile"":"""",""productNameL"":"""",""skuNameL"":"""",""skuCodeL"":"""",""productCodeL"":"""",""goodsOrSkuCnt"":"""",""finderName"":"""",""deliverPrintStatusList"":[0,1],""hasGift"":"""",""orderTypeList"":[],""orderTags"":[],""hasWaybillNo"":"""",""hasExpress"":"""",""cpCodeTempId"":"""",""receiveAreas"":[],""supplierIds"":[],""distributorIds"":[],""pageIndex"":200,""pageNo"":1,""limit"":500,""orderByIndex"":""13""}", Encoding.UTF8, "application/json");
            var response = await ErpHttpRequest(content, "Page");
            return response.Return_Count();
        }

        public async Task<JsonData> 获取数据_查询指定快递单号(string logisticsCodes)
        {
            var content = new StringContent(@$"{{""orderFlags"":[],""whId"":""1"",""platformCode"":"""",""mallCodes"":[],""orderCreateTimes"":[],""logisticsCodes"":[""{logisticsCodes}""],""buyerNicks"":[],""receiveMobileL4"":"""",""receiveName"":"""",""receiveMobile"":"""",""senderName"":"""",""senderPhone"":"""",""senderMobile"":"""",""productNameL"":"""",""skuNameL"":"""",""skuCodeL"":"""",""productCodeL"":"""",""goodsOrSkuCnt"":"""",""waybillPrintStatusList"":[0,1],""deliverPrintStatusList"":[0,1],""hasGift"":"""",""orderTypeList"":[],""orderTags"":[],""statusList"":[],""orderStatusList"":[],""hasWaybillNo"":"""",""hasExpress"":"""",""cpCodeTempId"":"""",""receiveAreas"":[],""supplierIds"":[],""distributorIds"":[],""pageIndex"":600,""pageNo"":1,""limit"":500,""orderByIndex"":""13""}}", Encoding.UTF8, "application/json");
            return await ErpHttpRequest(content, "Page");
        }
        public async Task<JsonData> 获取数据_申请1个新快递单号(View_订单 订单)
        {
            //0.正常单; 1.合单
            var content = 订单.mergeFlag=="1" ? new StringContent(@$"{{""againApply"":1,""companyId"":2507,""ifHasBuildPackageAuthority"":false,""mutilPackNum"":1,""userId"":""6d279c79c3984261a2217b7f1ab25849"",""orderInfoRequests"":[{{""applyOrderType"":1,""cpCode"":""{订单.cpCode}"",""cpCodeTempId"":""{订单.cpCodeTempId}"",""distributorPlatformCode"":"""",""id"":""{订单.id}"",""logisticsCodes"":[],""logisticsName"":""{订单.cpCodeName}"",""mallCode"":""{订单.mallCode}"",""mallName"":""{订单.mallName}"",""mergeId"":""{订单.mergeId}"",""mutilPackNum"":1,""orderId"":""{订单.orderId}"",""platformCode"":""{订单.platformCode}"",""subIds"":""{订单.mergeOrderIds}"",""sysOrderId"":""{订单.sysOrderId}""}}]}}", Encoding.UTF8, "application/json")
                                              : new StringContent(@$"{{""againApply"":1,""companyId"":2507,""ifHasBuildPackageAuthority"":false,""mutilPackNum"":1,""userId"":""6d279c79c3984261a2217b7f1ab25849"",""orderInfoRequests"":[{{""applyOrderType"":0,""cpCode"":""{订单.cpCode}"",""cpCodeTempId"":""{订单.cpCodeTempId}"",""distributorPlatformCode"":"""",""id"":""{订单.id}"",""logisticsCodes"":[],""logisticsName"":""{订单.cpCodeName}"",""mallCode"":""{订单.mallCode}"",""mallName"":""{订单.mallName}"",""mutilPackNum"":1,""orderId"":""{订单.orderId}"",""platformCode"":""{订单.platformCode}"",""subIds"":"""",""sysOrderId"":""{订单.sysOrderId}""}}]}}", Encoding.UTF8, "application/json")  ;
            return await ErpHttpRequest(content, "ApplyWaybill");
        }
        #endregion

        public async Task<JsonData> 回收快递单号(string id,string waybillNoList)
        {
            var content = new StringContent(@$"{{""recycleMode"":1,""orderInfoList"":[{{""id"":""{id}"",""waybillNoList"":[""{waybillNoList}""]}}]}}", Encoding.UTF8, "application/json");
            return await ErpHttpRequest(content, "RecycleWaybill");
        }

        public async Task<JsonData> 发货(string cpCode,string id,string logisticsCode,string mergeFlag,string orderId,string platformCode,string sysOrderId,string subIds)
        {
            var content = new StringContent(@$"{{""orderInfos"":[{{""cpCode"":""{cpCode}"",""id"":""{id}"",""logisticsCode"":""{logisticsCode}"",""mergeFlag"":{mergeFlag},""orderId"":""{orderId}"",""platformCode"":""{platformCode}"",""sysOrderId"":""{sysOrderId}"",""subIds"":""{subIds}"",""packgeId"":""""}}]}}", Encoding.UTF8, "application/json");
            return await ErpHttpRequest(content, "Send");
        }

        public async Task<JsonData> 获取车签数据()
        {
            var content = new StringContent($@"{{""orgCode"":""240094"",""opCode"":""130"",""containerNo"":""{Controller.车签}""}}", Encoding.UTF8, "application/json");
            return await ExpressHttpRequest(content, "InCar", Guid.NewGuid().ToString(), DateTime.Now);
        }

        public async Task<JsonData> 获取目的地数据(string 快递单号)
        {
            var content = new StringContent($@"{{""waybillNo"":""{快递单号}"",""orgCode"":""240094"",""mergeNo"":""01"",""opCode"":""310"",""companyCode"":""240094"",""checkMaterial"":""Y"",""inputWeight"":""0.20""}}", Encoding.UTF8, "application/json");
            return await ExpressHttpRequest(content, "Taking", Guid.NewGuid().ToString(),DateTime.Now);
        }

        public async Task<JsonData> 揽发合一操作(string ContainerNo, string DesOrgCode,string DesOrgName,string WaybillNo)
        {
            string guid = Guid.NewGuid().ToString();
            DateTime time = DateTime.Now;
            var content = new StringContent($@"{{""takingAndLoadList"":[{{""AuxOpCode"":""NEW"",""ContainerNo"":""{ContainerNo}"",""CreateOrgCode"":""240094"",""CreateUserCode"":""02639545"",""CustomerCode"":""K24071433"",""CustomerName"":""马利家"",""DesOrgCode"":""{DesOrgCode}"",""EmpCode"":""02591289"",""EmpName"":""潘茂宇"",""InputWeight"":0.2,""LineNo"":""MOT240094ATO240001A001"",""NextOrgCode"":""240001"",""NextOrgName"":""沈阳转运中心"",""OpCode"":""130"",""WeighWeight"":0.0,""DesOrgName"":""{DesOrgName}"",""LineName"":""沈阳市大东区七二四-沈阳"",""SwitchFlag"":""1010"",""osdFlag"":""0"",""ZLZP"":false,""scanFlag"":0,""UploadStatus"":1,""Id"":""{guid}"",""UploadResult"":""未上传"",""CreateTime"":""{time.ToString("yyyy-MM-dd HH:mm:s")}"",""WaybillNo"":""{WaybillNo}"",""CreateUserName"":""韩佳-Z""}}]}}", Encoding.UTF8, "application/json");
            return await ExpressHttpRequest(content, "TakingAndLoad",guid,time);
        }

       


        #region ·websocket
        public Task WebsocketConnect()
        {
            // return ws.ConnectAsync(new("ws://127.0.0.1:3300/print"), default);
            return ws.ConnectAsync(new("ws://127.0.0.1:13528"), default);//菜鸟打印组件
        }
        public Task WebsocketClose()
        {
            return ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "打印完成", CancellationToken.None);
        }
        public Task WebsocketSend(string message)
        {
            return ws.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(message)), WebSocketMessageType.Text, true, CancellationToken.None);
        }
        #endregion

        private async Task<JsonData> ErpHttpRequest(StringContent content, string requestName)
        {
            string url=string.Empty;
            HttpRequestMessage request = null;
            HttpResponseMessage response = null; ;
            switch (requestName)
            {
                case "Page":
                    url = "https://erp.yto.net.cn/erp/ecom-order/order/v2/tab/page"; break;

                case "ApplyWaybill":
                    url = "https://erp.yto.net.cn/erp/ecom-order/waybill/applyWaybill"; break;

                case "RecycleWaybill":
                    url = "https://erp.yto.net.cn/erp/ecom-order/order/recycleWaybill"; break;

                case "Send":
                    url = "https://erp.yto.net.cn/erp/ecom-order/delivery/send"; break;

            }

            try
            {
                request = new HttpRequestMessage(HttpMethod.Post, url);
                request.Content = content;
                request.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36 Edg/135.0.0.0");
                request.Headers.Add("Accept", "application/json");
                request.Headers.Add("accept-encoding", "gzip");
                request.Headers.Add("jwt-token", @$"{token}");
                response = await client.SendAsync(request);
                return await response.Content.ToJsonObj();
            }
            finally
            {
                if (null != content) content.Dispose();
                if (null != request) request.Dispose();
                if (null != response) response.Dispose();
            }

        }

        private async Task<JsonData> ExpressHttpRequest(StringContent content, string requestName,string guid,DateTime time)
        {
            string url = string.Empty;
            HttpRequestMessage request = null;
            HttpResponseMessage response = null; ;
            switch (requestName)
            {
                case "Taking":
                    url = "http://pdanew.yto56.com.cn:9097/pdaCheck/check/taking"; break;

                case "TakingAndLoad":
                    url = "http://pdanew.yto56.com.cn:9091/pdaUpload/op/takingAndLoad"; break;

                case "InCar":
                    url = "http://pdanew.yto56.com.cn:9097/pdaCheck/check/container/inCar"; break;
            }

            try
            {
                string token = "c11ef1b89cb2176d4f709e507681b177";
                string[] args = GetRequestId();
                request = new HttpRequestMessage(HttpMethod.Post, url);
                request.Content = content;
                request.Headers.Add("User-Agent", @"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; Maxthon; .NET CLR 1.1.4322)");
                request.Headers.Add("Accept", "application/json");
                request.Headers.Add("token", token);
              //  request.Headers.Add("loginUserCode", "02639545");
           //     request.Headers.Add("loginUserName", "%e9%9f%a9%e4%bd%b3");
                request.Headers.Add("requestID", args[2]);//Guid.NewGuid().ToString());
                request.Headers.Add("pdaDeviceType", "PC-N");
               // request.Headers.Add("MAC", "5C:B2:6D:CD:E4:A2");
               // request.Headers.Add("IP", "192.168.2.193");
               // request.Headers.Add("pdaVersionNo", "1.0.118");
                request.Headers.Add("pdaVersionCode", "101118");
                request.Headers.Add("orgCode", "240094");
                request.Headers.Add("time", args[1]);
              //  string timestamp = time.ToString("yyyyMMddHHmmssfff");
               // request.Headers.Add("timestamp", timestamp);
             //   string plainStr = string.Format("token={0}&orgCode={1}&timestamp={2}&secretKey={3}", new object[]
               // {
              //      token,
              //      "240094",
              //      timestamp,
              //      "5nj+X-ho6-MdJI(YO4XKw8CcyZt$ssZi"
               // });
               // request.Headers.Add("sign", Base64Md5(plainStr));

                response = await client.SendAsync(request);
                return await response.Content.ToJsonObj();
            }
            finally
            {
                if (null != content) content.Dispose();
                if (null != request) request.Dispose();
                if (null != response) response.Dispose();
            }
        }
        public static string GetTimeStamp()
        {
            return Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalMilliseconds).ToString();
        }
        public static string[] GetRequestId()
        {
            string securityKey = "c0^@*jsd&873*r63^*67(w%8(57";
            string[] args = new string[3];
            args[0] = "240094";
            args[1] = GetTimeStamp();
            args[2] = Base64Md5(string.Concat(new string[]
            {
                "orgCode",
                args[0],
                "time",
                args[1],
                securityKey
            }));
            return args;
        }
        public static string Base64Md5(string input)
        {
            return Convert.ToBase64String(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(input)));
        }
    }
    public class MergeSubOrder
    {
        public string id { get; set; }
        public string orderId { get; set; }
        public string sysOrderId { get; set; }
        public string orderStatus { get; set; }
        public List<Product> erpProducts { get; set; }
    }
    public class LogisticsCode
    {
        public string cpCode { get; set; }
        public string logisticsName { get; set; }
        public string waybillFlag { get; set; }
        public string logisticsCode { get; set; }
        public string isOutwaybill { get; set; }
    }
    public class Product
    { 
        public string id{ get; set; }
        public string subOrderId { get; set; }
        public string orderStatus { get; set; }
        public string productCode { get; set; }
        public string productName { get; set; }
        public string skuId { get; set; }
        public string skuCode { get; set; }
        public string productPic { get; set; }
        public int productNumber { get; set; }
        public string productSpecDesc { get; set; }
        public string productId { get; set; }


    }
    public class PrintData
    { 
        public string printer { get; set; }
        public string encryptedData { get; set; }
        public string signature { get; set; }
        public string templateURL { get; set; }
        public string ver { get; set; }
        public string printXML { get; set; }
    }

}
